import json
from common.settings import logger
from jsonpath import jsonpath
from common.constant import CommonErrorInfo


def get_value_from_response(response: str, json_path: str) -> str:
    if not response or not json_path:
        logger.error(CommonErrorInfo.RESPONSE_OR_JSONPATH_IS_NONE.value)
        raise ValueError(CommonErrorInfo.RESPONSE_OR_JSONPATH_IS_NONE.value)
    result = jsonpath(json.loads(response), json_path)
    logger.info(f'value from response: {result[0]}')
    return result[0]


if __name__ == '__main__':
    res = {
        "code": 200,
        "msg": "success",
        "data": [
            {
                "name": "张三",
                "age": 20
            },
            {
                "name": "李四",
                "age": 18
            }
        ]
    }
    value = get_value_from_response(json.dumps(res), "$.data[1].age")
    print(value)
    print(type(value))
